//
//  STMGoodsManagementViewController.m
//  StoreManagement
//
//  Created by centling on 16/5/20.
//  Copyright © 2016年 alfred. All rights reserved.
//

#import "STMGoodsManagementViewController.h"
#import "STMGoodsManagementTableViewCell.h"
#import "STMGoodsEditViewController.h"

@interface STMGoodsManagementViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *mainTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) BOOL refreshing;

@end

@implementation STMGoodsManagementViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:nGoodsManagementRefresh object:nil];
    
    self.mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-108)];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    self.mainTableView.rowHeight = 102;
    [self.mainTableView registerNib:[UINib nibWithNibName:@"STMGoodsManagementTableViewCell" bundle:nil] forCellReuseIdentifier:@"cellID"];
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mainTableView.mj_header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    self.mainTableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.mainTableView.mj_footer.automaticallyChangeAlpha = YES;
    self.mainTableView.mj_footer.automaticallyHidden = NO;
    [self.view addSubview:self.mainTableView];
    self.page = 1;
    self.refreshing = NO;
    [self loadData];
}

- (void)loadData {
    if (!self.refreshing) {
        self.refreshing = YES;
        [SVProgressHUD showWithStatus:@"加载中..."];
        [STMNetworkAPI getGoodsManagementListWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                                           goodsType:self.goodsType
                                                page:@"1"
                                             success:^(STMGoodsListModel *result) {
                                                 self.refreshing = NO;
                                                 [self.mainTableView.mj_header endRefreshing];
                                                 if ([result.code isEqualToString:@"200"]) {
                                                     self.page = 1;
                                                     [SVProgressHUD dismiss];
                                                     self.dataArray = [NSMutableArray arrayWithArray:result.result.goods_list];
                                                     [self.mainTableView reloadData];
                                                     if ([result.result.extend_data.hasmore isEqualToString:@"0"]) {
                                                         [self.mainTableView.mj_footer endRefreshingWithNoMoreData];
                                                         self.mainTableView.mj_footer.alpha = 1;
                                                     } else {
                                                         [self.mainTableView.mj_footer resetNoMoreData];
                                                         self.mainTableView.mj_footer.alpha = 0;
                                                     }
                                                     
                                                 } else if ([result.code isEqualToString:@"401"]) {
                                                     [GlobalUtil presentLoginVC];
                                                 } else {
                                                     [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                                 }
                                             }
                                             failure:^(NSError *err) {
                                                 self.refreshing = NO;
                                                 [self.mainTableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                                             }];
    }
}

//上拉加载
- (void)loadMoreData {
    self.page ++;
    if (!self.refreshing) {
        self.refreshing = YES;
        [SVProgressHUD showWithStatus:@"加载中..."];
        [STMNetworkAPI getGoodsManagementListWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                                           goodsType:self.goodsType
                                                page:[NSString stringWithFormat:@"%ld", self.page]
                                             success:^(STMGoodsListModel *result) {
                                                 self.refreshing = NO;
                                                 [self.mainTableView.mj_footer endRefreshing];
                                                 if ([result.code isEqualToString:@"200"]) {
                                                     [SVProgressHUD dismiss];
                                                     NSArray *newArray = result.result.goods_list;
                                                     [self.dataArray addObjectsFromArray:newArray];
                                                     NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];
                                                     for (NSInteger i = [self.mainTableView numberOfRowsInSection:0]; i <[self.dataArray count]; i++){
                                                         [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:i
                                                                                                           inSection:0]];
                                                     }
                                                     [self.mainTableView beginUpdates];
                                                     [self.mainTableView insertRowsAtIndexPaths:arrayWithIndexPaths withRowAnimation:UITableViewRowAnimationNone];
                                                     [self.mainTableView endUpdates];
                                                     if ([result.result.extend_data.hasmore isEqualToString:@"0"]) {
                                                         [self.mainTableView.mj_footer endRefreshingWithNoMoreData];
                                                         self.page --;
                                                         return;
                                                     }
                                                     
                                                 } else if ([result.code isEqualToString:@"401"]) {
                                                     self.page --;
                                                     [GlobalUtil presentLoginVC];
                                                 } else {
                                                     self.page --;
                                                     [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                                 }
                                             }
                                             failure:^(NSError *err) {
                                                 self.page --;
                                                 self.refreshing = NO;
                                                 [self.mainTableView.mj_footer endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                                             }];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    STMGoodsManagementTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID" forIndexPath:indexPath];
    cell.goodsType = self.goodsType;
    STMGoodsListDetail *cellData = self.dataArray[indexPath.row];
    cell.goodsDetailData = cellData;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    __weak __typeof(self)weakSelf = self;
    cell.cellBlock = ^{
        [weakSelf loadData];
    };
    return cell;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return 102;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    STMGoodsEditViewController *goodsEditVC = [[STMGoodsEditViewController alloc] init];
    [goodsEditVC customNavigationTitle:@"编辑商品"];
    STMGoodsListDetail *cellData = self.dataArray[indexPath.row];
    goodsEditVC.goodsCommonId = cellData.goods_commonid;
    UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    [nav pushViewController:goodsEditVC animated:YES];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
